/**
 * 
 */
package cn.mabach.oauth2.validateCode;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.mabach.oauth2.utils.RegexUtils;
import cn.mabach.oauth2.constant.RedisConstant;
import cn.mabach.oauth2.properties.SecurityProperties;
import cn.mabach.oauth2.utils.RS;
import cn.mabach.oauth2.validateCode.imageCode.ValidateCodeGenerator;
import cn.mabach.oauth2.validateCode.smsCode.SendCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhailiang
 *
 */
@RestController
@Slf4j
public class CodeController {




	@Autowired
	private SecurityProperties securityProperties;


	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	private ValidateCodeGenerator validateCodeGenerator;
	@Autowired
	private SendCode sendCode;

	/**
	 * 生成验证码:调用KaptchaConfig生成图形验证码
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/code/image")
	public void imageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 1. 获取验证码字符串
		String code = RandomStringUtils.randomNumeric(4);
		log.info("生成的图形验证码是：" + code);
		// 2. 字符串把它放到redis中中
		String id = request.getSession().getId();

		stringRedisTemplate.boundHashOps(RedisConstant.KAPTCHA_KEY).put(id,code);
		stringRedisTemplate.expire(id,securityProperties.getCode().getImage().getExpireIn(),TimeUnit.SECONDS);
		// 3. 获取验证码图片
		BufferedImage image = validateCodeGenerator.createCode(code);
		// 4. 将验证码图片把它写出去
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
	}


	@RequestMapping("/code/mobile")
	public RS smsCode(@RequestParam(value = "mobile") String mobile,HttpServletRequest request){
		boolean b = RegexUtils.checkMobile(mobile);
		if (!b){
			return RS.error("手机号格式不正确");
		}

		String code = RandomStringUtils.randomNumeric(securityProperties.getCode().getSmsCode().getLength());



		stringRedisTemplate.boundValueOps(mobile).set(code,securityProperties.getCode().getSmsCode().getExpireIn(),TimeUnit.SECONDS);

		String s = stringRedisTemplate.boundValueOps(mobile).get();
		log.info("redis去除的：{}",s);
		log.info("使用mq发送短信");

		sendCode.send(mobile,code);
		return RS.ok();

	}


}
